package com.zbkj.common.utils;

import com.zbkj.common.exception.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDate;
import java.util.Objects;

/**
 * @Auther: liuxiaowei
 * @Date: 2022-4-1 12:33
 * @Description:
 */
@Slf4j
@Component
public class FileUtil {

    public final static String WORD_DOC = ".doc";
    public final static String WORD_DOCX = ".docx";

    /**
     * 下载图片
     * @param filePath
     * @return
     * @throws IOException
     */
    public static byte[] downloadNetFile(String filePath) throws Exception {
        HttpURLConnection httpconn = null;
        InputStream inputStream = null;
        try (ByteArrayOutputStream swapStream = new ByteArrayOutputStream();){
            URL url =new URL(filePath); // 创建URL
            URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码
            httpconn =(HttpURLConnection)urlconn;
            httpconn.setConnectTimeout(10*1000);
            httpconn.setReadTimeout(30*1000);
            if(httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                //int filesize = urlconn.getContentLength(); // 取数据长度
                inputStream = httpconn.getInputStream();
                int ch;
                byte[] buffer = new byte[8*1024];
                while ((ch = inputStream.read(buffer)) != -1) {
                    swapStream.write(buffer,0,ch);
                }
                return swapStream.toByteArray();
            } else {
                throw new Exception("图片地址打开失败");
            }
        } catch (Exception e) {
            log.error("downloadNetFile-程序异常：{}",e);
            throw new Exception("图片下载程序异常"+e.getMessage());
        } finally {
            if(httpconn != null) {
                httpconn.disconnect();
            }
            if(inputStream != null) {
                inputStream.close();
            }
        }
    }

    public static void downNetFileToFile(String netUrl, File outFile) throws Exception {
        HttpURLConnection httpconn = null;
        InputStream inputStream = null;
        FileUtil.dirCreate(outFile.getParentFile());
        try (OutputStream os = new FileOutputStream(outFile);){
            URL url =new URL(netUrl); // 创建URL
            URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码
            httpconn =(HttpURLConnection)urlconn;
            httpconn.setConnectTimeout(10*1000);
            httpconn.setReadTimeout(30*1000);
            if(httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                //int filesize = urlconn.getContentLength(); // 取数据长度
                inputStream = httpconn.getInputStream();
                //IOUtils.copy(inputStream,os);
                int ch;
                byte[] buffer = new byte[10*1024];
                while ((ch = inputStream.read(buffer)) != -1) {
                    os.write(buffer,0,ch);
                }
                os.flush();
            } else {
                log.error("downloadNetFile-netUlr:{}-文件地址打开失败",netUrl);
                throw new Exception("文件地址打开失败");
            }
        } catch (Exception e) {
            log.error("downloadNetFile-netUlr:{}-程序异常:",netUrl,e);
            throw new Exception("文件下载程序异常");
        } finally {
            if(httpconn != null) {
                httpconn.disconnect();
            }
            if(inputStream != null) {
                inputStream.close();
            }
        }
    }

    public static void dirCreate(File dirFile) {
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
    }


    public static String readDoc(FileInputStream fis) throws Exception{
        String text = null;
        try(HWPFDocument document = new HWPFDocument(fis);
            WordExtractor extractor = new WordExtractor(document);) {
            text = extractor.getText();
            //document.getRange().text()
        }
        return text;
    }
    public static String readDocx(FileInputStream fis) throws Exception{
        String text = null;
        //ZipSecureFile.setMinInflateRatio(0.001);
        try (XWPFDocument document = new XWPFDocument(fis);
             XWPFWordExtractor extractor = new XWPFWordExtractor(document);){
            text = extractor.getText();
        }
        return text;
    }

    /**
     * 对取word文档内容
     * @param netUrl
     * @param fileName
     * @param tmpPathPrex
     * @return
     */
    public static String readNetWordContent(String netUrl, String fileName, String tmpPathPrex) {
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String dateStr = LocalDateUtil.localDateToStr(LocalDate.now(),LocalDateUtil.YYYYMMDD);
        String tempFilePath = FilenameUtils.separatorsToSystem(String.format("%s%s/%s%s",tmpPathPrex,dateStr,CommonUtil.getUuid(),fileType));
        File tempFile = new File(tempFilePath);
        FileInputStream fileIn = null;
        try {
            String text = null;
            downNetFileToFile(netUrl,tempFile);
            fileIn = new FileInputStream(tempFile);
            if(WORD_DOC.equals(fileType.toLowerCase())) {
                text = readDoc(fileIn);
            } else if(WORD_DOCX.equals(fileType.toLowerCase())) {
                text = readDocx(fileIn);
            } else {
                throw new CommonException(fileName+"文件类型错误");
            }
            if(Objects.isNull(text)) {
                throw new CommonException(fileName+"文件读取失败");
            }
            return text;
        } catch (CommonException ce) {
            throw ce;
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("{}文件读取异常-error:",fileName,e);
            //e.printStackTrace();
            throw new CommonException(fileName+"文件读取错误");
        } finally {
            if(fileIn != null) {
                try {
                    fileIn.close();
                } catch (IOException e) {
                }
            }
            if(tempFile.exists() && tempFile.isFile()) {
                tempFile.delete();
            }
        }
    }

    /**
     * 读取word文档字符数
     * @param netUrl
     * @param fileName
     * @param tmpPathPrex
     * @return
     */
    public static long readNetWordCharCount(String netUrl, String fileName, String tmpPathPrex) {
        long start = System.currentTimeMillis();
        String text = readNetWordContent(netUrl, fileName, tmpPathPrex);
        long charNum = Long.valueOf(text.length());
        text = null;
        log.info("fileName:{}-读取字符数:{}-耗时:{}ms",netUrl,charNum,(System.currentTimeMillis()-start));
        return charNum;
    }

    public static String subFileName(String name) {
        String fileName = name;
        if(StringUtils.isBlank(name)) {
            return fileName;
        }
        int lastIdx = name.lastIndexOf(".");
        if(lastIdx > 0) {
            fileName = fileName.substring(0,lastIdx);
        }
        return fileName;
    }
}
